package tech.runchen.gz5055.oms.security.service;

import com.lrinfo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import tech.runchen.gz5055.oms.common.constant.Constant;
import tech.runchen.gz5055.oms.common.exception.RRException;
import tech.runchen.gz5055.oms.common.manager.AsyncManager;
import tech.runchen.gz5055.oms.common.manager.factory.AsyncFactory;
import tech.runchen.gz5055.oms.common.utils.ServletUtils;
import tech.runchen.gz5055.oms.common.utils.StringUtils;
import tech.runchen.gz5055.oms.common.utils.ip.IpUtils;
import tech.runchen.gz5055.oms.modules.system.entity.FingerprintEntity;
import tech.runchen.gz5055.oms.modules.system.entity.UserEntity;
import tech.runchen.gz5055.oms.modules.system.service.IFingerprintService;
import tech.runchen.gz5055.oms.modules.system.service.IUserService;
import tech.runchen.gz5055.oms.security.model.LoginUser;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class LoginService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private IUserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private IFingerprintService fingerprintService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constant.LOGIN_FAIL, "用户不存在/密码错误"));
                throw new RRException("用户不存在/密码错误");
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constant.LOGIN_FAIL, e.getMessage()));
                throw new RRException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constant.LOGIN_SUCCESS, "登录成功"));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 登录验证
     *
     * @param psChar 指纹特征
     * @return
     */
    public String login(String psChar) {
        // 用户验证
        Authentication authentication = null;
        try {
            //指纹登录
            Long userId = fingerprintService.checkFingerprint(psChar);
            UserEntity user = userService.getById(userId);
            if (userId == null || user == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor("指纹特征：" + psChar, Constant.LOGIN_FAIL, "指纹不匹配"));
                throw new RRException("指纹不匹配");
            }
            UserDetails userDetails = new LoginUser(user.getId(), user, permissionService.getMenuPermission(user));
            authentication = new UsernamePasswordAuthenticationToken(userDetails, null, AuthorityUtils.createAuthorityList("ROLE_USER"));
        } catch (Exception e) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor("指纹特征：" + psChar, Constant.LOGIN_FAIL, e.getMessage()));
            throw new RRException(e.getMessage());
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor("指纹特征：" + psChar, Constant.LOGIN_SUCCESS, "登录成功"));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public void logout(LoginUser loginUser) {
        tokenService.delLoginUser(loginUser.getToken());
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        UserEntity user = new UserEntity();
        user.setId(userId);
        user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        user.setLoginDate(LocalDateTime.now());
        userService.updateUser(user);
    }
}
